import Vue from 'vue'
import PromptVue from './prompt.vue'

const PromptConstructor = Vue.extend(PromptVue)
const instance = new PromptConstructor({
  el: document.createElement('div')
})

PromptConstructor.prototype.closePrompt = function () {
  const el = instance.$el
  el.parentNode && el.parentNode.removeChild(el)
  typeof this.callback === 'function' && this.callback()
}

const Prompt = (options = {}) => {
  const isString = typeof options === 'string'
  instance.title = isString ? options : options.title
  if (!isString) {
    instance.placeholder = options.placeholder
    instance.multiple = options.multiple
  }
  instance.callback = options.callback

  document.body.appendChild(instance.$el)

  return new Promise((resolve, reject) => {
    instance.$on('closePrompt', () => {
      resolve(null)
      instance.closePrompt()
    })

    instance.$on('submit', (val) => {
      resolve(val || null)
      instance.closePrompt()
    })
  })
}

export default Prompt
